package com.contest.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.contest.constant.CommonsConstant;
import com.contest.entity.UserInfo;
import com.contest.entity.WarSituationInfo;
import com.contest.entity.WarSituationSetup;
import com.contest.service.RoomInfoService;
import com.contest.service.UserInfoService;
import com.contest.service.WarSituationInfoService;
import com.contest.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * @author yfl
 * @email 617823298@qq.com
 * @date 2017-12-20 16:30:37
 */

@Controller
@RequestMapping("/warSituationInfo")
public class WarSituationInfoController {

    @Autowired
    WarSituationInfoService warSituationInfoService;
    @Autowired
    IdWorker idWorker;
    @Autowired
    UserInfoService userInfoService;

    @RequestMapping("/list")
    @ResponseBody
    public PageUtils list(@RequestParam Map<String, Object> param) {
        int page = Integer.parseInt(param.get("page").toString());
        int rows = Integer.parseInt(param.get("rows").toString());
        Map<String, Object> map = new HashMap<>();
        map.put("start", page);
        map.put("rows", rows);
        String o = String.valueOf(param.get("name"));
        if (o != null && !o.equals("") && !o.equals("null")) {
            map.put("fdname", o);
        }

        List<WarSituationInfo> list = warSituationInfoService.selectListByPage(map);
        return new PageUtils(list, warSituationInfoService.selectByPageCount(map));
    }

    @PostMapping("/save")
    @ResponseBody
    public R save(WarSituationInfo warSituationInfo) {
        warSituationInfo.setFdId(idWorker.nextId() + "");
        if (warSituationInfoService.insert(warSituationInfo)) {
            return R.ok("操作成功!");
        } else {
            return R.error("操作失败");
        }
    }

    @GetMapping("/edit/{fdId}")
    public String edit(Model model, @PathVariable("fdId") String fdId) {
        WarSituationInfo warSituationInfo = warSituationInfoService.selectById(fdId);
        String createId = warSituationInfo.getFdCreateId();
        String dareId = warSituationInfo.getFdDareId();
        warSituationInfo.setFdCreateId(userInfoService.selectById(createId).getFdNickname());
        warSituationInfo.setFdDareId(userInfoService.selectById(dareId).getFdNickname());
        model.addAttribute("warSituationInfo", warSituationInfo);
        return "warSituationInfo/edit";
    }

    @PostMapping("/remove")
    @ResponseBody
    public R remove(@RequestParam("ids[]") String[] ids) {
        List<String> fdIds = new ArrayList<String>();
        for (String id : ids) {
            fdIds.add(id);
        }
        if (warSituationInfoService.deleteBatchIds(fdIds)) {
            return R.ok("删除成功");
        } else {
            return R.error(-1, "删除失败!");
        }
    }

    @PostMapping("/update")
    @ResponseBody
    public R update(WarSituationInfo warSituationInfo) {
        if (warSituationInfoService.updateResult(warSituationInfo)) {
            return R.ok("更新成功!");
        } else {
            return R.error(-1, "更新失败!");
        }
    }


    @RequestMapping("/client/check")
    @ResponseBody
    public R check(HttpServletRequest request,Integer type){
        UserInfo userInfo = UserLoginUtil.getCurrentUserInfo(request);
        if(type == 0){
            //发布
            EntityWrapper<WarSituationInfo> infoEntityWrapper = new EntityWrapper<WarSituationInfo>();
            infoEntityWrapper.addFilter("fd_create_id={0} and fd_is_end={1}",userInfo.getFdId(),0);
            List<WarSituationInfo> infoList = warSituationInfoService.selectList(infoEntityWrapper);
            if (infoList.size() != 0){
                return R.ok(infoList.get(0));
            }
        }else{
            //挑战
            EntityWrapper<WarSituationInfo> infoEntityWrapper = new EntityWrapper<WarSituationInfo>();
            infoEntityWrapper.addFilter("fd_dare_id={0} and fd_is_end={1}",userInfo.getFdId(),0);
            List<WarSituationInfo> infoList = warSituationInfoService.selectList(infoEntityWrapper);
            if (infoList.size() != 0){
                return R.ok(infoList.get(0));
            }
        }
        return R.ok("0");
    }

    @PostMapping("/client/publish")
    @ResponseBody
    public R publish(WarSituationInfo warSituationInfo, HttpServletRequest request) throws ParseException {
        int mode = warSituationInfo.getFdWarMode();
        UserInfo userInfo = UserLoginUtil.getCurrentUserInfo(request);
        warSituationInfo.setFdCreateId(userInfo.getFdId());
        warSituationInfo.setCreateWinRate(RandomUtil.getRate());
        warSituationInfo.setFdIsEnd(0);
        UserInfo over = userInfoService.selectById(userInfo.getFdId());
        float amount = warSituationInfo.getFdAmount().floatValue();
        if (mode == 1) {
            //加密
            String tempPwd = String.valueOf(System.currentTimeMillis());
            String pwd = tempPwd.substring(tempPwd.length() - 4, tempPwd.length());
            warSituationInfo.setFdPwd(pwd);
            if (!userInfoService.checkUserOver(userInfo.getFdId(), amount)) {
                return R.error("发布战局失败,余额不足!");
            } else {
                over.setFdOver(BigDecimal.valueOf(over.getFdOver().floatValue() - amount));
                userInfoService.updateById(over);
                warSituationInfo.setFdId(idWorker.nextId()+"");
                warSituationInfoService.insert(warSituationInfo);
                return R.ok(warSituationInfo);
            }
        } else {
            //大厅
            if(!userInfoService.checkUserOver(over.getFdId(),amount)){
                return R.error("发布战局失败,余额不足!");
            }else{
                over.setFdOver(BigDecimal.valueOf(over.getFdOver().floatValue() - amount));
                userInfoService.updateById(over);
                warSituationInfo.setFdId(idWorker.nextId()+"");
                warSituationInfoService.insert(warSituationInfo);
                return R.ok(warSituationInfo);
            }
        }
    }

    @PostMapping("/client/dare")
    @ResponseBody
    public R dare(String roomNo,String pwd, Integer mode, HttpServletRequest request) {
        UserInfo userInfo = UserLoginUtil.getCurrentUserInfo(request);
        UserInfo over = userInfoService.selectById(userInfo.getFdId());
        if(mode == 1){
            //加密
            EntityWrapper<WarSituationInfo> infoEntityWrapper = new EntityWrapper<>();
            infoEntityWrapper.addFilter("fd_room_no={0} and fd_pwd={1} and fd_war_mode={2}",roomNo,pwd,mode);
            infoEntityWrapper.isNull("fd_dare_id");
            WarSituationInfo info = warSituationInfoService.selectOne(infoEntityWrapper);
            if(info == null){
                return R.error("房间密码错误!");
            }else{
                float amount = info.getFdAmount().floatValue();
                if(userInfoService.checkUserOver(over.getFdId(),amount)){
                    float overAmount = over.getFdOver().floatValue();
                    over.setFdOver(BigDecimal.valueOf(overAmount - amount));
                    userInfoService.updateById(over);
                    info.setFdDareId(userInfo.getFdId());
                    warSituationInfoService.updateById(info);
                    return R.ok(100,"挑战成功!");
                }else{
                    return R.error("挑战失败,余额不足!");
                }
            }
        }else{
            //大厅
            EntityWrapper<WarSituationInfo> infoEntityWrapper = new EntityWrapper<>();
            infoEntityWrapper.addFilter("fd_room_no={0} and fd_war_mode={1}",roomNo,mode);
            infoEntityWrapper.isNull("fd_dare_id");
            WarSituationInfo info = warSituationInfoService.selectOne(infoEntityWrapper);
            if (info == null){
                return R.error("房间不存在!");
            }else{
                float amount = info.getFdAmount().floatValue();
                if(userInfoService.checkUserOver(over.getFdId(),amount)){
                    float overAmount = over.getFdOver().floatValue();
                    over.setFdOver(BigDecimal.valueOf(overAmount - amount));
                    userInfoService.updateById(over);
                    info.setFdDareId(userInfo.getFdId());
                    warSituationInfoService.updateById(info);
                    return R.ok(100,"挑战成功!");
                }else{
                    return R.error("挑战失败,余额不足!");
                }
            }
        }
    }

    @PostMapping("/client/updateResult")
    @ResponseBody
    public R updateResult(String warId, Integer result, String screenshots, HttpServletRequest request, HttpServletResponse response) {
        UserInfo userInfo = UserLoginUtil.getCurrentUserInfo(request);
        String pic = Base64UploadPic.base64UpLoad(screenshots, "image", request, response);
        if (warSituationInfoService.updateResultByUser(userInfo, warId, result, pic)) {
            return R.ok();
        } else {
            return R.error();
        }
    }


    @PostMapping("/client/getRoomNo")
    @ResponseBody
    public R getRoomNo() {
        String time = String.valueOf(System.currentTimeMillis());
        String roomNo = "VIP" + time.substring(time.length() - 7, time.length() - 1);
        Map<String, Object> map = new HashMap<>();
        map.put("fd_room_no", roomNo);
        return R.ok(map);
    }


    @PostMapping("/client/getRoomInfo")
    @ResponseBody
    public R getRoomInfo(String fdId) {
        WarSituationInfo info = warSituationInfoService.selectById(fdId);
        if (info == null) {
            return R.error("房间不存在！");
        } else {
            return R.ok(info);
        }
    }

    @PostMapping("/client/getPKRecord")
    @ResponseBody
    public R getPKRecord(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        UserInfo userInfo = UserLoginUtil.getCurrentUserInfo(request);
        map.put("fd_create_id", userInfo.getFdId());
        map.put("fd_is_settlement", "1");
        List<WarSituationInfo> infoList = warSituationInfoService.selectByMap(map);

        Map<String, Object> map2 = new HashMap<>();
        map2.put("fd_dare_id", userInfo.getFdId());
        map2.put("fd_is_settlement", "1");
        List<WarSituationInfo> infoList2 = warSituationInfoService.selectByMap(map2);

        infoList.addAll(infoList2);

        if (infoList == null || infoList.size() == 0) {
            return R.ok("暂无战局记录！");
        } else {
            return R.ok(infoList);
        }
    }

    @PostMapping("/client/upWarPic")
    @ResponseBody
    public R upWarPic(String warId, String result, String picType, String base64Data, HttpServletRequest request, HttpServletResponse response) {
        UserInfo userInfo = UserLoginUtil.getCurrentUserInfo(request);
        String path = Base64UploadPic.base64UpLoad(base64Data, "image", request, response);
        WarSituationInfo war = warSituationInfoService.selectById(warId);
        if (picType != null && picType.length() > 0) {
            if (picType.equals("0")) {
                war.setFdCreatePic(path);
                war.setFdCreateResult(Integer.parseInt(result));
            }
            if (picType.equals("1")) {
                war.setFdDarePic(path);
                war.setFdDareResult(Integer.parseInt(result));
            }
        }
        if (warSituationInfoService.updateById(war)) {
            return R.ok("上传成功!");
        } else {
            return R.error("上传失败!");
        }
    }


    @PostMapping("/client/listWars")
    @ResponseBody
    public R listWars(HttpServletRequest request, Integer mode) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        UserInfo userInfo = UserLoginUtil.getCurrentUserInfo(request);
        Wrapper<WarSituationInfo> w = new EntityWrapper();
        //w.and("fd_start_time > {0}", sdf.format(new Date())).and("(fd_create_id={0}", userInfo.getFdId()).or("fd_dare_id={0})", userInfo.getFdId());
        w.and("fd_start_time > {0}", sdf.format(new Date())).and("fd_is_settlement={0}", 0);
        if (mode != null || mode != -1) {
            w.and("fd_war_mode={0}", mode);
        }
        w.isNull("fd_dare_id");
        List<WarSituationInfo> infoList = warSituationInfoService.selectList(w);
        DecimalFormat df = new DecimalFormat("######0.00");
        for (WarSituationInfo ws : infoList) {
            String userid = ws.getFdCreateId();
            UserInfo user = userInfoService.selectById(userid);
            double win = Double.parseDouble(user.getFdWinNum());
            double lose = Double.parseDouble(user.getFdLoseNum());
            double total = win + lose;
            if (total != 0) {
                String rate = df.format((win / total) * 100) + "%";
                ws.setCreateWinRate(rate);
            } else {
                ws.setCreateWinRate("暂无比赛记录");
            }

        }
        if (infoList == null || infoList.size() == 0) {
            return R.error("当前无对战房间！");
        } else {
            return R.ok(infoList);
        }
    }

    @RequestMapping("/client/getWarInfo")
    @ResponseBody
    public R getWarInfo(String pwd) {
        Map<String, Object> map = new HashMap<>();
        map.put("fd_pwd", pwd);
        List ls = warSituationInfoService.selectByMap(map);
        return R.ok(ls);
    }


    @RequestMapping("/client/getWarInfoByNo")
    @ResponseBody
    public R getWarInfoByNo(String warNo) {
        Wrapper<WarSituationInfo> w = new EntityWrapper<>();
        w.like("fd_room_no", warNo).and("fd_is_settlement<>1");
        List ls = warSituationInfoService.selectList(w);
        return R.ok(ls);
    }


    @RequestMapping("/client/getPking")
    @ResponseBody
    public R getPking(HttpServletRequest request) {
        UserInfo userInfo = UserLoginUtil.getCurrentUserInfo(request);
        Wrapper<WarSituationInfo> w = new EntityWrapper();
        w.and("fd_create_id={0}", userInfo.getFdId()).and("fd_dare_id is not null")
                .and("fd_is_settlement <> 1");
        WarSituationInfo war = warSituationInfoService.selectOne(w);
        if (war != null) {
            return R.ok(war);
        }

        Wrapper<WarSituationInfo> w2 = new EntityWrapper();
        w2.and("fd_create_id is not null").and("fd_dare_id={0}", userInfo.getFdId())
                .and("fd_is_settlement <> 1");
        WarSituationInfo war2 = warSituationInfoService.selectOne(w2);
        if (war2 != null) {
            return R.ok(war2);
        }
        return R.error("当前不在对战中！");
    }


}
